# coding:utf-8
import urllib
import sys
import os
import pics
import log
import config
class Search:
    save_dir = config.save_root + 'tag/'
    search_url = 'https://www.pixiv.net/search.php'
    tag = ''
    R18 = False
    search = {}
    search['s_mode'] = 's_tag'
    search['order'] = 'popular_d'

    def __init__(self, tag, r18 = True, start = 1, end = 10, opener = None):
        self.opener = opener
        self.tag = tag
        self.R18 = r18
        self.start = start
        self.end = end
        self.search['p'] = start
        self.tag_encode()
        if self.R18:
            self.search['mode'] = 'r18'
            self.save_dir += 'ex/' + self.tag
        else:
            self.search['mode'] = 'safe'
            self.save_dir += 'normal/' + self.tag
        print self.save_dir
        self.mkdir()
        if self.opener != None:
            self.begin()

    def mkdir(self):
        if not os.path.exists(self.save_dir):
            os.makedirs(self.save_dir)

    def tag_encode(self):
        self.search['word'] = urllib.quote(self.tag.encode('utf-8'))

    def url_encode(self):
        l = []
        query = self.search
        query = query.items()
        for k, v in query:
            k = str(k)
            v = str(v)
            l.append(k + '=' + v)
        a = '&'.join(l)
        return self.search_url + '?' + a

    def begin(self):
        for i in range(self.start,self.end + 1):
            url = self.url_encode()

            pics.Pics(url=url, dir=self.save_dir, tag = self.tag, opener=self.opener)
            if self.R18:
                l = log.Log()
                l.ex_log(tag=self.tag,page=i)
            else:
                l = log.Log()
                l.normal_log(tag=self.tag,page=i)
            self.search['p'] += 1
